package logging

import (
	"fmt"
	"github.com/natefinch/lumberjack"
	"path/filepath"
	"runtime"
	"strings"
)

var lumberjackLogger *lumberjack.Logger

func LumberjackLogger(cfg LogConfig) *lumberjack.Logger {
	if lumberjackLogger == nil {
		lumberjackLogger = &lumberjack.Logger{
			Filename:   cfg.FilePath,
			MaxSize:    200,
			MaxAge:     7,
			MaxBackups: 50,
			Compress:   true,
		}
	}
	return lumberjackLogger
}

func LumberjackRotate() error {
	if lumberjackLogger == nil {
		return nil
	}
	return Wrap(lumberjackLogger.Rotate())
}

// Wrap .
func Wrap(err error, info ...any) error {
	if err == nil {
		return nil
	}

	_, file, line, ok := runtime.Caller(1)
	if !ok {
		file = "Unknown"
		line = -1
	}

	file = strings.TrimSuffix(filepath.Base(file), ".go")

	if len(info) == 0 {
		return fmt.Errorf("%s:%d > %w", file, line, err)
	}

	return fmt.Errorf("%s:%d%v > %w", file, line, info, err)
}
